package com.sharp.framework.controller;

import com.sharp.framework.utils.HttpUtil;
import com.sharp.framework.utils.file.FreeMarkerUtil;
import com.sharp.framework.utils.file.PdfUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * Title: PdfExportController
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2019/12/24 下午6:02
 * @description Project Name: customer
 * @Package: com.bhfae.customer.app.manage.controller
 */
@Slf4j
@Api(value = "", tags = "pdf文件流")
@RestController
@RequestMapping(value = "/swagger/pdf")
public class PdfExportController {

    @ApiOperation(value = "获取pdf文件流", notes = "上传ftl文件,获取pdf文件流")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public void exportPdfByFtl(MultipartFile file, HttpServletResponse response) throws IOException {
        File htmlFile = File.createTempFile("html", null);
        File pdfFile = File.createTempFile("pdf", null);
        file.transferTo(htmlFile);
        String html = FreeMarkerUtil.freemarkerRender(new HashMap<>(0), htmlFile);
        PdfUtil.createPdfByHtmlTemplate(pdfFile, html, null, "");
        mergeStream(file.getName(), pdfFile, response);
        htmlFile.deleteOnExit();
        pdfFile.deleteOnExit();

    }

    private void mergeStream(String fileName, File file, HttpServletResponse response) {
        response.reset();
        response.setContentType("application/pdf");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".pdf");
        HttpUtil.mergeStream(file, response);
    }
}
